<template>
  <el-row class="hl-header-box">
    <el-col :span="10" class="align-items">
      <el-icon style="cursor:pointer;" @click="setColl" v-if="!store.isCollapse" :size="20" color="#929395">
        <Fold />
      </el-icon>
      <el-icon style="cursor:pointer;" @click="setColl" v-else :size="20" color="#B52427">
        <Expand />
      </el-icon>
      <div class="compony-system-font">市十一中管理平台，欢迎您~</div>
    </el-col>
    <el-col :span="14">
      <el-row justify="end" class="align-items">
        <span class="times">{{ TimeStamp }}</span>
        <div class="personImg">
          <img class="avatar" :src="useSto.userInfo && useSto.userInfo.inch ? useSto.userInfo.inch : personImg" />
        </div>
        <el-dropdown @command="handleCommand">
          <span class="el-dropdown-link">
            {{ useSto.userInfo ? useSto.userInfo.name : '' }}
            <el-icon class="el-icon--right">
              <CaretBottom />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item icon="User" command="user">修改密码</el-dropdown-item>
              <el-dropdown-item icon="SwitchButton" command="return">退出系统</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-row>
    </el-col>
  </el-row>
  <!-- 修改密码弹窗 -->
  <Model title="修改密码" :modelShow="passModelShow" width="480" @cancel="Cancel(ruleFormRef)"
    @confirm="Confirm(ruleFormRef)">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="80px" status-icon>
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="ruleForm.oldPassword" placeholder="请输入旧密码" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="ruleForm.newPassword" placeholder="请输入新密码" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="ruleForm.confirmPassword" placeholder="请确认新密码" type="password" show-password />
      </el-form-item>
    </el-form>
  </Model>
</template>
<script setup lang="ts">
import axios from 'axios'
import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router'
import { PiniaStore } from '../../store'
import { useMeanStore } from '../../store/menus'
import { useUserStore } from '../../store/user'
import type { FormInstance, FormRules } from 'element-plus'
// import noDateImg from '../../assets/images/ikon_no message.png'
import personImg from '../../assets/images/edit.png'
import { logout } from '../../components/Api/login'
import { getTime } from '../../components/Api/index'
const router = useRouter()
const store = PiniaStore()
const useSto = useUserStore()
const useMean = useMeanStore()
const setColl = () => {
  store.setCollapse(!store.isCollapse)
}
const handleCommand = async (command: any) => {
  if (command === 'return') {
    const res: any = await logout()
    if (res.code !== 1) return ElMessage.error(res.msg)
    window.sessionStorage.clear()
    window.localStorage.clear()
    useMean.changeRouteStatus(false)
    useSto.remove()
    router.replace({ path: '/login' })
  } else if (command === 'user') {
    // 修改密码
    router.push({ name: 'EditPwd', query: { type: 10101 } })
  }
}
const equalToPassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.newPassword !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
const passModelShow = ref(false)
const ruleForm = reactive<any>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: "旧密码不能为空", trigger: "blur" }
  ],
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { required: true, validator: equalToPassword, trigger: "blur" }
  ]
})
const Cancel = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  passModelShow.value = false
  // emit('modelCancel', false)
}
// 点击确定编辑或者新增
const Confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid: any) => {
    if (valid) {
      const obj = {
        oldPassword: ruleForm.oldPassword,
        newPassword: ruleForm.newPassword
      }
      // const res: any = await updateUserPwd(obj)
      // if (res.code !== 200) return ElMessage.error(res.msg)
      // ElMessage.success('修改成功')
      axios.request({
        url: '/system/user/profile/updatePwd',
        method: 'put',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: obj
      }).then(res => {
        if (res.data.code !== 200) return ElMessage.error(res.data.msg)
        ElMessage.success(res.data.msg)
        passModelShow.value = false
        formEl.resetFields()
      })
    } else {
      console.log('error submit!')
    }
  })
}
// 获取服务器时间
const Time = ref<any>('')
const nowDate = ref<any>('')
const TimeStamp = ref<any>('')
const nowTimeStamp = ref<any>('')
// 当前时间戳（10位）
const nowDateTime = async () => {
  nowDate.value = Math.round(new Date().getTime() / 1000).toString()
  nowDate.value = parseInt(nowDate.value)
  timestampToTime(nowDate.value)
  nowTimeStamp.value = await timestampToTime(nowDate.value)
}
const timestampToTime = async (timestamp: any) => {
  var date = new Date(timestamp * 1000)// 时间戳若为10位时需*1000
  // var date = new Date(timestamp); // 时间戳若为13位则不需要乘1000
  var Y = date.getFullYear()
  var M = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
  var D = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate()
  var h = date.getHours() >= 10 ? date.getHours() : '0' + date.getHours()
  var m = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes()
  var s = date.getSeconds() >= 10 ? date.getSeconds() : '0' + date.getSeconds()
  return `${Y}年${M}月${D}日 ${h}:${m}:${s}`
}
// 获取服务器时间
const getTimeStamp = async () => {
  const res: any = await getTime()
  if (res.code !== 1) return ElMessage.error(res.msg)
  Time.value = JSON.parse(res.data.time)
  nowDateTime()
  TimeStamp.value = await timestampToTime(Time.value)
}
onMounted(async () => {
  getTimeStamp()
  setInterval(async () => {
    Time.value++
    nowDate.value++
    TimeStamp.value = await timestampToTime(Time.value)
    nowTimeStamp.value = await timestampToTime(nowDate.value)
  }, 1000)
})
</script>
<style lang="scss" scoped>
.hl-header-box {
  height: 60px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  color: #333333;
  font-size: 16px;
  padding: 0 20px;

  .iconColl {
    display: inline-block;
    vertical-align: middle;
    cursor: pointer;
  }

  .title {
    display: inline-block;
    vertical-align: middle;
  }

  .times {
    margin-right: 20px;
  }

  .avator-flex-box {
    margin-right: 15px;
  }

  .personImg {
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    border-radius: 50%;
    // background: var(--el-color-primary);;
    margin-right: 15px;
    color: #ffffff;

    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      display: inline-block;
    }
  }

  .compony-system-font {
    margin-left: 10px;
    color: #333;
    font-size: 16px;
    margin-top: -1px;
  }
}

:deep(.el-avatar) {
  background: transparent;
}
</style>
